package Presentacion;

import Clases.AdelantoAguinaldo;
import Clases.Aguinaldo;
import Clases.AguinaldoId;
import Clases.Empleado;
import Clases.Pago;
import Control.ControlAdelantoAguinaldo;
import Control.ControlEmpleado;
import Control.ControlPago;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class ManejoAguinaldo extends javax.swing.JFrame {

    ControlPago controlP = ControlPago.obtenerInstancia();
    ControlAdelantoAguinaldo controlA = ControlAdelantoAguinaldo.obtenerInstancia();
    ControlEmpleado controlE = ControlEmpleado.obtenerInstancia();
    private TableRowSorter sorter = new TableRowSorter();

    public ManejoAguinaldo() {
        initComponents();
        jTextField1.setToolTipText("Ingrese cédula o código del empleado.");
        jButton2.setToolTipText("Se genera el aguinaldo para todos los empleados.");
    }
    private static ManejoAguinaldo instancia = null;

    public static ManejoAguinaldo obtenerInstancia() {
        if (instancia == null) {
            instancia = new ManejoAguinaldo();
        }
        return instancia;
    }

    public void init() {
        setTitle("Aguinaldo");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sorter.setModel(jTable1.getModel());
        jTable1.setRowSorter(sorter);
        jTextField1.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        newFilter();
                    }
                });
        llenarTablaAguinaldos();
        this.setVisible(true);
    }

    private void newFilter() {
        RowFilter<DefaultTableModel, Object> cedulaFilter = null;
        RowFilter<DefaultTableModel, Object> nombreFilter = null;
        List<RowFilter<DefaultTableModel, Object>> filters = new ArrayList<RowFilter<DefaultTableModel, Object>>();
        RowFilter<DefaultTableModel, Object> compoundRowFilter = null;
        try {
            cedulaFilter = RowFilter.regexFilter("(?i)^" + jTextField1.getText(), 0);
            nombreFilter = RowFilter.regexFilter("(?i)^" + jTextField1.getText(), 1);
            filters.add(cedulaFilter);
            filters.add(nombreFilter);
            compoundRowFilter = RowFilter.orFilter(filters);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(compoundRowFilter);
    }

    public void llenarTablaAguinaldos() {
        ArrayList<Aguinaldo> aguinaldos = controlP.obtenerListaAguinaldos();
        DefaultTableModel m = (DefaultTableModel) jTable1.getModel();
        try {
            while (m.getRowCount() > 0) {
                m.removeRow(0);
            }
            for (int i = 0; i < aguinaldos.size(); i++) {
                Empleado empleado = controlE.getEmpleadoNum(aguinaldos.get(i).getId().getNumEmpleado());
                m.insertRow(m.getRowCount(), new Object[]{empleado.getCodigo(),
                    empleado.getNombre() + " " + empleado.getApellido1(), aguinaldos.get(i).getAguinaldo()});
            }
        } catch (Exception e) {
            System.out.println(e.getCause());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(640, 350));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Buscar:");

        jTextField1.setToolTipText("Ingrese la cédula o nombre del empleado");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("Adelanto de Aguinaldo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Generar Aguinaldo");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Nombre", "Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel5.setText("Aguinaldo");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 598, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(260, 260, 260)
                .addComponent(jLabel5)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int confirmado = JOptionPane.showConfirmDialog(null, "¿Está seguro que quiere generar el aguinaldo para todos los empleados?");
        Object exito = null;
        if (JOptionPane.OK_OPTION == confirmado) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date date = new Date();
            String[] fecha = dateFormat.format(date).split("/");
            int month = Integer.valueOf(fecha[1]);
            int day = Integer.valueOf(fecha[2]);

            if (month == 12 && (day >= 1 && day <= 21)) {
                ArrayList<Empleado> empleados = controlE.obtenerListaEmpleados();
                for (int i = 0; i < empleados.size(); i++) {
                    double totalAguinaldo = this.calcularAguinaldo(empleados.get(i));
                    AguinaldoId id = new AguinaldoId(date, empleados.get(i).getNumEmpleado());
                    Aguinaldo aguinaldo = new Aguinaldo(id, empleados.get(i), totalAguinaldo);
                    exito = controlP.insertarAguinaldo(aguinaldo);
                }
                if (exito == null) {
                    JOptionPane.showMessageDialog(null, "El aguinaldo ya fue generado", "Mensaje", JOptionPane.ERROR_MESSAGE);
                } else {
                    this.llenarTablaAguinaldos();
                    JOptionPane.showMessageDialog(null, "El aguinaldo se generó correctamente para todos los empleados", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

                }
            } else {
                JOptionPane.showMessageDialog(null, "El aguinaldo no se puede generar todavía", "Mensaje", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed
    public double calcularAguinaldo(Empleado empleado) {
        double totalAguinaldo = 0.0;
        ArrayList<Pago> pagos = controlP.getPagosPorNumEmpleado(empleado.getNumEmpleado());
        double suma = 0;
        double sumaAdelantos = 0;
        Double prom = 0.0;
        int cantMeses = pagos.size();
        if (cantMeses % 2 != 0) {  // quiere decir cant d mes inexacto x lo cual cuanto hasta mes anterios compeletamente laborado     
            cantMeses = cantMeses - 1;
            pagos.remove(pagos.size() - 1); // remuevo la ultima quincena xq no la tomare en cuenta, cuenta hasta nov
        }
        if (cantMeses <= 12) {
            for (int i = 0; i < pagos.size(); i++) {
                suma += pagos.get(i).getSalarioBase();
            }
            prom = suma / 12;
        }
        ArrayList<AdelantoAguinaldo> adelantos = controlA.getAdelantoEmpleado(empleado.getNumEmpleado());
        if (adelantos.isEmpty()) {
            totalAguinaldo = (prom * cantMeses) / 12; //revisar estos calculos
        } else {
            for (int i = 0; i < adelantos.size(); i++) {
                sumaAdelantos += adelantos.get(i).getAdelanto();
            }
            totalAguinaldo = ((prom * cantMeses) / 12) - sumaAdelantos;
        }

        return totalAguinaldo;
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        ManejoAdelantoAguinaldo.obtenerInstancia().limpiar();
        ManejoAdelantoAguinaldo.obtenerInstancia().init();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManejoAguinaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManejoAguinaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManejoAguinaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManejoAguinaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        JFrame.setDefaultLookAndFeelDecorated(true);
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManejoAguinaldo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
